package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.CartBo;
import com.cskaoyan.bean.bo.CartCheckedBo;
import com.cskaoyan.bean.bo.CartCheckoutBo;
import com.cskaoyan.bean.vo.CartBaseVo;
import com.cskaoyan.bean.vo.CartCheckeoutVo;
import com.cskaoyan.bean.vo.CartIndexVo;
import com.cskaoyan.bean.vo.CartTotal;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.WXShoppingService;
import com.cskaoyan.service.WxCouponServiceZGY;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WXShoppingServiceImpl implements WXShoppingService {
    @Autowired
    CskaoyanmallUserMapper userMapper;
    @Autowired
    CskaoyanmallCartMapper cartMapper;
    @Autowired
    CskaoyanmallGoodsProductMapper goodsProductMapper;
    @Autowired
    CskaoyanmallAddressMapper addressMapper;

    @Autowired
    CskaoyanmallGoodsMapper goodsMapper;

    @Autowired
    CskaoyanmallCouponMapper couponMapper;
    @Autowired
    WxCouponServiceZGY wxCouponServiceZGY;
@Autowired
CskaoyanmallSystemMapper systemMapper;
    static BigDecimal goodsTotalPrice;




    @Override
    //购物车初始化页面
    public CartIndexVo cartIndex(CskaoyanmallUser user) {
        CartIndexVo cartIndexVo = new CartIndexVo();
        //获取用户的id
        Integer id = user.getId();
        //通过id查询该用户的购物车订单
        CartBaseVo cartIndex = getCartIndex(id);//
        cartIndexVo.setCartList(cartIndex.getCartList());
        CartTotal cartTotal = cartIndex.getCartTotal();
        cartIndexVo.setCartTotal(cartTotal);
        return cartIndexVo;
    }

    @Override
    //选择购物车订单
    public CartIndexVo cartCheckedService(CartCheckedBo bo, CskaoyanmallUser user) {
        CskaoyanmallCartExample cartExample = new CskaoyanmallCartExample();
        CskaoyanmallCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId()).andProductIdIn(bo.getProductIds());

        CskaoyanmallCart cart = new CskaoyanmallCart();
        cart.setChecked(bo.getIsChecked());

        int i = cartMapper.updateByExampleSelective(cart, cartExample);
        CartIndexVo cartIndexVo = cartIndex(user);
        return cartIndexVo;
    }

    @Override
    //添加购物车
    public Long cartAddService(CskaoyanmallCart bo, CskaoyanmallUser user) {

        addCart(bo,user);
        CskaoyanmallCartExample example = new CskaoyanmallCartExample();
        example.createCriteria().andUserIdEqualTo(user.getId()).andDeletedEqualTo(false);
        long total = cartMapper.countByExample(example);
        return total;
    }

    @Override
    //修改购物车
    public int cartUpdateService(CskaoyanmallCart bo,CskaoyanmallUser user) {
        bo.setUserId(user.getId());
        int i = cartMapper.updateByPrimaryKeySelective(bo);
        return i;
    }

    @Override
    public int cartDeleteService(Map<String, List<Integer> > map , CskaoyanmallUser user) {
        List<Integer> productIds = map.get("productIds");
        CskaoyanmallCartExample cartExample = new CskaoyanmallCartExample();
        cartExample.createCriteria().andUserIdEqualTo(user.getId()).
                andProductIdIn(productIds).andDeletedEqualTo(false);
        CskaoyanmallCart cart = new CskaoyanmallCart();
        cart.setDeleted(true);

        int i = cartMapper.updateByExampleSelective(cart, cartExample);
        return i;

    }

    @Override
    public Integer cartGoodscountService(CskaoyanmallUser user) {
        CskaoyanmallCartExample cartExample = new CskaoyanmallCartExample();
        cartExample.createCriteria().andUserIdEqualTo(user.getId()).andDeletedEqualTo(false);
        int count = 0;
        List<CskaoyanmallCart> cartList = cartMapper.selectByExample(cartExample);
        for (CskaoyanmallCart cc:cartList) {
            count+=(int)cc.getNumber();
        }
        return count;
    }

    @Override
    public Integer cartFastaddService(CskaoyanmallCart bo, CskaoyanmallUser user) {
        addCart(bo,user);
        CskaoyanmallCartExample example = new CskaoyanmallCartExample();
        return bo.getId();

    }
    //添加购物车
    private void addCart(CskaoyanmallCart bo, CskaoyanmallUser user) {
        CskaoyanmallCart cart = cartMapper.queryCartInfo(bo.getGoodsId(), bo.getProductId());
        cart.setUserId(user.getId());
        cart.setGoodsId(bo.getGoodsId());
        cart.setProductId(bo.getProductId());
        cart.setNumber(bo.getNumber());

        CskaoyanmallCartExample cartExample = new CskaoyanmallCartExample();
        cartExample.createCriteria().andUserIdEqualTo(user.getId()).
                andGoodsIdEqualTo(bo.getGoodsId()).
                andProductIdEqualTo(bo.getProductId()).
                andDeletedEqualTo(false);

        List<CskaoyanmallCart> cartList = cartMapper.selectByExample(cartExample);
        if (!cartList.isEmpty()) {
            for (CskaoyanmallCart cl : cartList) {
                short number = (short) (bo.getNumber() + cl.getNumber());
                cl.setNumber(number);
                cl.setUpdateTime(new Date());
                cartMapper.updateByPrimaryKey(cl);
            }
        } else {
            cart.setAddTime(new Date());

            cart.setChecked(true);
            cart.setDeleted(false);
            cartMapper.insertSelective(cart);
        }
    }


    @Override
    public CartCheckeoutVo cartCheckoutService(CartCheckoutBo bo, CskaoyanmallUser user) {
        CartCheckeoutVo checkeoutVo = new CartCheckeoutVo();

        Integer addressId = bo.getAddressId();
        Integer cartId = bo.getCartId();
        Integer couponId = bo.getCouponId();
        Integer grouponRulesId = bo.getGrouponRulesId();

         //获取用户订单list，total
        CartBaseVo cartIndex = getCartIndex(user.getId());

        //需要下单订单list
        List<CskaoyanmallCart> cartList = cartIndex.getCartList();
        ArrayList<CskaoyanmallCart> checkedGoodsList = new ArrayList<>();
        for (CskaoyanmallCart cart : cartList) {
            if (cart.getChecked()){
                checkedGoodsList.add(cart);
            }
        }
        checkeoutVo.setCheckedGoodsList(checkedGoodsList);

        //传入地址,以及地址id
        CskaoyanmallAddress checkedAddress = addressMapper.selectByPrimaryKey(addressId);
        checkeoutVo.setCheckedAddress(checkedAddress);
        checkeoutVo.setAddreeId(addressId);
        //商品总计金额
        BigDecimal goodsTotalPrice = cartIndex.getCartTotal().getCheckedGoodsAmount();
        checkeoutVo.setGoodsTotalPrice(goodsTotalPrice);

        //用户所有的优惠卷数量

        List<CskaoyanmallCoupon> allCoupons = wxCouponServiceZGY.queryAvailableCoupons(cartId, bo.getCouponId(), user.getId());
        List<CskaoyanmallCoupon> coupons =new ArrayList<>();
        for (CskaoyanmallCoupon cc:allCoupons) {
            //过滤无效优惠卷
            if (goodsTotalPrice.compareTo(cc.getMin())>=0) {
                coupons.add(cc);
            }
        }
        int availableCouponLength=0;
        if (coupons!=null) {
            availableCouponLength = coupons.size();
        }
        checkeoutVo.setAvailableCouponLength(availableCouponLength);

        //优惠卷金额 以及优惠卷id
        BigDecimal couponPrice = new BigDecimal(0);

            CskaoyanmallCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
        if (coupon!=null) {
            couponPrice = coupon.getDiscount();
        }
        checkeoutVo.setCouponPrice(couponPrice);
        checkeoutVo.setCouponId(couponId);


        //
        //下单付费时的实际金额
        BigDecimal actualPrice;
        actualPrice = goodsTotalPrice.subtract(couponPrice);
        checkeoutVo.setActualPrice(actualPrice);
        //运费 满88包邮，不满10块钱运费
        BigDecimal freighPrice = new BigDecimal(0);

        CskaoyanmallSystemExample systemExample = new CskaoyanmallSystemExample();
        systemExample.createCriteria().andIdEqualTo(37);
        List<CskaoyanmallSystem> systems = systemMapper.selectByExample(systemExample);
        CskaoyanmallSystem system = systems.get(0);
        String value = system.getKeyValue();
        Integer num = Integer.valueOf(value);


        if (goodsTotalPrice .compareTo(BigDecimal.valueOf(num))>=0 ) {
            CskaoyanmallSystem system1 = systemMapper.selectByPrimaryKey(39);

            Integer yunfei = Integer.valueOf(system1.getKeyValue());
            freighPrice.add(BigDecimal.valueOf(yunfei));
        }
        checkeoutVo.setFreightPrice(freighPrice);

        //订单金额等于实付金额
        BigDecimal orderTotalPrice ;
        orderTotalPrice = actualPrice;
        checkeoutVo.setOrderTotalPrice(orderTotalPrice);

        //团购不用写，设置为零
        BigDecimal grouponPrice = new BigDecimal(0);//团购不用写，设置为零
        checkeoutVo.setGrouponPrice(grouponPrice);
        checkeoutVo.setGrouponRulesId(grouponRulesId);
        this.goodsTotalPrice = goodsTotalPrice;
        return checkeoutVo;
    }

    //获取用户订单list，total
    public CartBaseVo getCartIndex(Integer id){
        CartBaseVo result = new CartBaseVo();

        // 获取当前用户购物车中的商品信息
        CskaoyanmallCartExample cartExample = new CskaoyanmallCartExample();
        cartExample.createCriteria().andUserIdEqualTo(id).andDeletedEqualTo(false);

        List<CskaoyanmallCart> cartList = cartMapper.selectByExample(cartExample);
        result.setCartList(cartList);

        //添加总数，价格总数
        Integer goodsCount = 0;
        Integer checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount = new BigDecimal(0);

        for (CskaoyanmallCart cart : cartList) {
            goodsCount = goodsCount + cart.getNumber();
            BigDecimal price = cart.getPrice();

            BigDecimal multiply = price.multiply(BigDecimal.valueOf(cart.getNumber()));
            goodsAmount=goodsAmount.add(multiply);
            if (cart.getChecked()) {
                checkedGoodsCount = checkedGoodsCount + cart.getNumber();

                BigDecimal checkedprice = cart.getPrice();
                BigDecimal checkedmultiply = checkedprice.multiply(BigDecimal.valueOf(cart.getNumber()));
                checkedGoodsAmount = checkedGoodsAmount.add(checkedmultiply);
            }

        }

        CartTotal cartTotal = new CartTotal();
        cartTotal.setGoodsCount(goodsCount);
        cartTotal.setGoodsAmount(goodsAmount);
        cartTotal.setCheckedGoodsCount(checkedGoodsCount);
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount);
        result.setCartTotal(cartTotal);
        return result;
    }

    /**
     * 以下三个方法为订单调用
     *
     * @param cartId
     * @param userId
     * @return
     */
    @Override
    public List<CskaoyanmallCart> getCheckedGoodsList(Integer cartId,Integer userId){
        //if cartId == 0 购物车里所有选中的商品
        //获取已选的购物车商品列表

        CskaoyanmallCartExample cartExample = new CskaoyanmallCartExample();
        CskaoyanmallCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false)
                .andUserIdEqualTo(userId)
                .andCheckedEqualTo(true);
        //if cartId !=0 显示当前购物车id里的商品
        if (cartId != 0) {
            criteria.andIdEqualTo(cartId);
        }
        return cartMapper.selectByExample(cartExample);
    }



    @Override
    public void deleteCart(Integer cartId) {
        CskaoyanmallCart cart = new CskaoyanmallCart();
        cart.setId(cartId)
                .setDeleted(true);
        cartMapper.updateByPrimaryKeySelective(cart);
    }


    @Override
    public void clearGoods(Integer userId) {

        CskaoyanmallCartExample example = new CskaoyanmallCartExample();
        example.or().andUserIdEqualTo(userId).andCheckedEqualTo(true);
        CskaoyanmallCart cart = new CskaoyanmallCart();
        cart.setDeleted(true);
        cartMapper.updateByExampleSelective(cart, example);
    }
}
